package com.hcy.app.screen.miao

import android.Manifest
import android.content.pm.PackageManager.PERMISSION_GRANTED
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.ScrollableTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.content.ContextCompat
import androidx.hilt.navigation.compose.hiltViewModel
import com.hcy.app.LocalNavController
import kotlinx.coroutines.launch


@Composable
fun Idp_Home(idpViewModel: IDPViewModel = hiltViewModel() ){
    val navController = LocalNavController.current
    val ctx = LocalContext.current
    val locationPermissions = Manifest.permission.ACCESS_FINE_LOCATION

    val idpInfoState by idpViewModel.idpInfoState.collectAsState()
    val idpConfState by idpViewModel.idpConfState.collectAsState()

    // 创建权限启动器
    val permissionLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.RequestPermission(),
        onResult = {
        }
    )
    // 进入页面时触发权限检查
    LaunchedEffect(Unit) {
        if (ContextCompat.checkSelfPermission(ctx, locationPermissions) != PERMISSION_GRANTED) {
            permissionLauncher.launch(locationPermissions) // 自动弹出权限请求对话框
        }else{
            idpViewModel.updateIdpInfo(ctx)
        }
    }

    if (idpConfState.showConfDialog) {
        AlertDialog(
            onDismissRequest = { idpConfState.showConfDialog },
            title = { Text("标题") },
            text = {
                Column {
                    OutlinedTextField(
                        value = idpConfState.serAddr,
                        onValueChange = { idpViewModel.updateConfSerAddr(it) },
                        modifier = Modifier.fillMaxWidth(),
                        label = { Text("请输入服务器信息") },
                        placeholder = { Text(text = "http://123.57.147.147:19005") },
                    )
                }
            },

            confirmButton = {
                TextButton(onClick = { idpViewModel.updateConfDialog(false) }) {
                    Text("确定")
                }
            },
            dismissButton = {
                TextButton(onClick = { idpViewModel.updateConfDialog(false) }) {
                    Text("取消")
                }
            }
        )
    }
    // 屏幕骨架
    Column(
        modifier = Modifier.fillMaxSize()
            .systemBarsPadding()
            .background(Color(0xFFE51C23)).padding(2.dp)
    ) {
        // 标签设置栏、设置按钮
        Row (
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ){
            Text(
                text = "IDP信息采集",
                modifier = Modifier.weight(1f),
                color = Color.White,
                fontSize = 26.sp,
                textAlign = TextAlign.Center
            )
            IconButton(
                onClick = { idpViewModel.updateConfDialog(true) },
                content ={
                    Icon(
                        imageVector = Icons.Default.Settings,
                        contentDescription = "设置",
                        tint = Color.White
                    )
                },
            )
            IconButton(
                onClick = { navController.navigate("home") },
                content ={
                    Icon(
                        imageVector = Icons.Default.Home,
                        contentDescription = "首页",
                        tint = Color.White
                    )
                },
            )
        }

        // Tabs 标签页，显示采集详情信息
        val tabs = listOf("基础信息","扩展信息", "NFC", "RFID","虚拟应用")
        val pagerState = rememberPagerState { tabs.size } // 总页数
        val coroutineScope = rememberCoroutineScope() // 用于启动协程

        Column {
            ScrollableTabRow(
                selectedTabIndex = pagerState.currentPage,
                containerColor = Color.Transparent,
                contentColor = MaterialTheme.colorScheme.onSurface,
                edgePadding = 8.dp,
            ) {
                tabs.forEachIndexed { index, model ->
                    Tab(
                        text = { Text(model) },
                        selected = pagerState.currentPage == index,
                        onClick = {
                            coroutineScope.launch {
                                pagerState.animateScrollToPage(index)
                            }
                        },
                    )
                }
            }
            // 2. 横向滑动页面
            HorizontalPager(
                state = pagerState,
                modifier = Modifier.weight(1f)
            ) { pageIndex ->
                when(pageIndex){
                    0->IDP_Info()
                    1->Box(
                        modifier = Modifier.fillMaxSize().background(Color.Yellow),
                        contentAlignment = Alignment.Center
                    ) {
                        Text("我是第二个页面")
                    }
                    else -> Box(
                        modifier = Modifier.fillMaxSize().background(Color.Red),
                        contentAlignment = Alignment.Center
                    ) {
                        Text("我是第default页面")
                    }
                }
            }
            // 3. 同步 Tab 点击与 Pager 滑动
            LaunchedEffect(pagerState.currentPage) {
                // 自动滚动到对应页面（可选）
                pagerState.animateScrollToPage(pagerState.currentPage)
            }
        }
    }

}



